package com.service.impl;

import com.api.CodeService;
import com.api.UserService;
import com.entity.TokenEntity;
import com.entity.UserEntity;
import com.repository.TokenRepository;
import com.repository.UserRepository;

import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;


import javax.transaction.Transactional;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository repository;
    @Reference
    private CodeService codeService;
    @Autowired
    private TokenRepository tokenRepository;

    @Override
    public Integer register(String email, String password, String code) {
        if (isRegistered(email)) {
            return 1;
        }
        if (codeService.validate(email, code)) {
            createUser(email, password);
            return 0;
        }else{
            return 2;
        }
    }

    private TokenEntity createToken(String email) {
        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setEmail(email);
        tokenEntity.setToken(UUID.randomUUID().toString());
        tokenRepository.save(tokenEntity);
        return tokenEntity;
    }

    private void createUser(String email, String password) {
        UserEntity userEntity = new UserEntity();
        userEntity.setEmail(email);
        userEntity.setPassword(password);
        repository.save(userEntity);
    }

    @Override
    public boolean isRegistered(String email) {
        UserEntity user = repository.findByEmail(email);
        return user != null;
    }

    @Override
    public TokenEntity login(String email, String password) {
        UserEntity user = repository.findByEmail(email);
        if (user != null && user.getPassword().equals(password)) {
            return createToken(email);
        }
        return null;
    }

    @Override
    public TokenEntity info(String token) {
        return tokenRepository.findByToken(token);
    }
}
